import re
from docx import Document
from word.wordTableEntity import WordTableEntity


class WordGenerate:
    def __init__(self, wordPath):
        self.wordPath = wordPath

    def getWordTableData(self, index):
        doc = Document(self.wordPath)
        table = doc.tables
        t = table[index]
        if len(t.rows) == 0:
            return None
        i = 0
        wordTable = {}
        try:
            startRule = re.compile('^[a-zA-z]{1}.*$')
            for k in range(1, len(t.rows)):
                filed = t.cell(k, 0).text
                if filed == "" or startRule.match(str(filed)) is None:
                    continue
                desc = t.cell(k, 1).text
                filedType = t.cell(k, 2).text
                filedType = self.judyFiledType(filedType)
                ruleDesc = t.cell(k, 3).text
                word = WordTableEntity(filedName=filed, filedType=filedType, rules=ruleDesc, desc=desc)
                wordTable[i] = word
                i += 1
            return wordTable
        except:
            return None

    def getTables(self):
        doc = Document(self.wordPath)
        return len(doc.tables)

    def judyFiledType(self, filed):
        fileType = filed
        filedTypeArray = ['string', 'integer']
        if "[" in fileType:
            fileType = fileType.split("[")[0]
        if fileType in filedTypeArray:  # 转换字母大写
            fileType = str(fileType).capitalize()
        return fileType


if __name__ == "__main__":
    doc = Document('mytest.docx')
    table = doc.tables
    print(len(table))
    # for i in range(1, len(t.rows)):
    #     print(t.cell(i, 0).text, t.cell(i, 2).text)
    #     print('-------')
